<?php
namespace app\erp_meixingtiyu\model;

use think\Model;
use think\model\concern\SoftDelete;
use app\common\model\store\User as StoreUserModel;
use app\common\model\User as UserModel;

use app\common\enum\order\PayStatus as OrderPayStatusEnum;
use \DateTime;
use \DateTimeZone;

class Booking extends Model
{
  use SoftDelete;
  protected $deleteTime = 'delete_time';
  protected $table = 'athlon_arena_booking';

  public function getPayTimeAttr($value)
  {
    $datetime = DateTime::createFromFormat('U', $value);
    return $datetime->setTimezone(new DateTimeZone('Asia/Shanghai'))->format('Y-m-d H:i:s');
  }

  // 关联的多个时段信息
  public function fragments()
  {
    return $this->hasMany(BookingFragment::class, 'booking_id');
  }

  public function referees()
  {
    return $this->hasMany(BookingReferee::class, 'booking_id');
  }

  // 获取后台管理员操作的预订记录
  public function getListWithAdmin()
  {
    return self::with('fragments')->withAttr('user_id', function($value, $data) {
      return StoreUserModel::find($value)->visible(['store_user_id', 'real_name']);
    })->where('book', config('arena.book.admin'))->order('create_time desc')->paginate(10);
  }

  // 获取前台用户的预订记录
  public function getListWithUser()
  {
    return self::with(['fragments', 'referees'])->withAttr('user_id', function($value, $data) {
      return UserModel::find($value);
    })->where('book', config('arena.book.user'))->order('pay_time', 'desc')->paginate(10);
  }

  public function selectListByDate($startDate, $endDate) {
    return self::with('fragments')->withAttr('user_id', function($value, $data) {
      return UserModel::find($value);
    })->where('book', config('arena.book.user'))->where('pay_status', OrderPayStatusEnum::SUCCESS)->order('pay_time desc')->whereBetweenTime('pay_time', $startDate, $endDate)->select();
  }

  // 前台下单预订
  public function order($userId, $date, $total, $fragments)
  {
    return $this->transaction(function () use ($userId, $date, $total, $fragments) {
        $order = self::create([
          'user_id' => $userId,
          'book' => 1,
          'order_no' => $this->createOrderNo(),
          'start_date' => $date,
          'end_date' => $date,
          'total_price' => $total
        ]);

        $order->fragments()->saveAll($fragments);
        return $order;
    });

  }

  /**
   * 生成订单号
   * @return string
   */
  public function createOrderNo()
  {
    return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 9);
  }

  public function getOrderById($id)
  {
    return self::find($id);
  }

  public function getOrdersByDate($date)
  {
    return self::with('fragments')->where('pay_status', OrderPayStatusEnum::SUCCESS)->whereDay('pay_time', $date)->select();
  }

}
